﻿using Microsoft.Practices.Unity;
using UnityDemo.InstanceManagerCode.LifeTimeModels;
using UnityDemo.Models;

namespace UnityDemo.InstanceManagerCode.LifetimeTypes
{
    internal class ContainerConrtolledLifeTimeManagerDemo : ISample
    {
        //ContainerControlledLifetimeManager. Unity returns the same instance of the registered type or object
        //each time you call the Resolve or ResolveAll method or when the dependency mechanism injects
        //instances into other classes. This lifetime manager effectively implements a singleton behavior for objects.
        //Unity uses this lifetime manager by default for the RegisterInstance method if you do not specify a different
        //lifetime manager. If you want singleton behavior for an object that Unity creates when you use
        //the RegisterType method, you must explicitly specify this lifetime manager.
        //The behavior is as follows: If you used the RegisterType method to register a type,
        //Unity creates a new instance of the registered type during the first call to the Resolve or ResolveAll
        //method or when the dependency mechanism injects instances into other classes.
        //Subsequent requests return the same instance.
        //If you used the RegisterInstance method to register an existing object,
        //Unity returns this instance every time you call the Resolve or ResolveAll method or
        //when the dependency mechanism injects instances into other classes.
        public ContainerConrtolledLifeTimeManagerDemo()
        {
            var container = new UnityContainer();
            container.RegisterType<SingletonInstance>(new ContainerControlledLifetimeManager());
            var singleInstance1 = container.Resolve<SingletonInstance>();
            singleInstance1.PrintHashCode();

            var singleInstance2 = container.Resolve<SingletonInstance>();
            singleInstance2.PrintHashCode();
        }
    }
}